package com.xiaoma.thread.wait;

/**
 * @author xiaomacdut
 * @date 2020年2月21日 下午10:06:16
 */
public class WaitTest {
    
    public static void main(String [] args)  {
        Object obj = new Object();
        ThreadA t1 = new ThreadA(obj);


        synchronized(obj){//t1和main线程用的同一个锁对象
            try{
                // 启动“线程t1”
                System.out.println(Thread.currentThread().getName() + " start t1");
                t1.start();

                System.out.println(Thread.currentThread().getName() + " wait()");
                // main线程等待，t1线程来唤醒main
                obj.wait();
                System.out.println(Thread.currentThread().getName() + " continue");
                
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        
        
    }
    
    static class ThreadA extends Thread{
        
        // 这个lock 就对应前面的obj对象
        private Object lock;
        
        /**
         * @param lock
         */
        public ThreadA(Object lock){
            super();
            this.lock = lock;
        }
        
        public ThreadA(String name){
            super(name);
        }
        
        public void run(){
            synchronized(this.lock){
                try{
                    Thread.sleep(1000);
                }catch(Exception e){
                    
                }
                System.out.println(Thread.currentThread().getName() + " call notify()");
                lock.notify();
                
            }
        }
        
/*        public void run(){
            synchronized(this){
                try{
                    this.wait(1000);
                    Thread.sleep(1000); // 使当前线阻塞 1 s，确保主程序的 t1.wait(); 执行之后再执行 notify()
                }catch(Exception e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " call notify()");
                // 唤醒当前的wait线程
                this.notify();
            }
        }*/
    }
}
